package task

import (
	"gitea.in/wx-rdc/service-base/internal/pkg/core"
	"gitea.in/wx-rdc/service-base/internal/repository/mysql"
)

type SearchData struct {
	Page       int     `json:"page"`
	PageSize   int     `json:"page_size"`
	Title      *string `json:"title"`       // 任务名称
	Status     *int32  `json:"status"`      // 任务状态
	CategoryId *int32  `json:"category_id"` // 任务分类
	UserId     *int32  `json:"user_id"`     // 任务负责人
	DueAt      *int64  `json:"due_at"`      // 任务截止时间
}

type TaskItem struct {
	Id            int32  `json:"id"`
	Title         string `json:"title"`
	Content       string `json:"content"`
	Status        int32  `json:"status"`
	DutAt         int64  `json:"dut_at"`
	CategoryId    int32  `json:"category_id"`
	CategoryTitle string `json:"category_title"`
	UserId        int32  `json:"user_id"`
	Username      string `json:"username"`
	Fullname      string `json:"fullname"`
	CreatedAt     int64  `json:"created_at"`
	UpdatedAt     int64  `json:"updated_at"`
}

func (s *service) List(ctx core.Context, searchData *SearchData) (total int64, list []*TaskItem, err error) {
	page := searchData.Page
	if page == 0 {
		page = 1
	}

	pageSize := searchData.PageSize
	if pageSize == 0 {
		pageSize = 10
	}

	offset := (page - 1) * pageSize

	db := s.db.GetDbR().WithContext(ctx.RequestContext()).
		Table("task t").
		Select("t.*, u.username, u.fullname, c.title as category_title").
		Joins("LEFT JOIN user u ON t.user_id = u.id").
		Joins("LEFT JOIN category c ON t.category_id = c.id")

	// 字符串模糊查询
	if searchData.Title != nil {
		db = db.Where(mysql.LikePredicate, "%"+*searchData.Title+"%")
	}
	if searchData.Status != nil {
		db = db.Where(mysql.EqualPredicate, *searchData.Status)
	}
	if searchData.UserId != nil {
		db = db.Where(mysql.EqualPredicate, *searchData.UserId)
	}
	if searchData.CategoryId != nil {
		db = db.Where(mysql.EqualPredicate, *searchData.CategoryId)
	}
	// 时间类型
	if searchData.DueAt != nil {
		db = db.Where(mysql.SmallerThanOrEqualPredicate, *searchData.DueAt)
	}

	err = db.Count(&total).Error
	if err != nil {
		return
	}

	// order
	db = db.Order("t.created_at DESC")

	// 分页
	db = db.Limit(pageSize).Offset(offset)

	// scan results
	list = []*TaskItem{}
	err = db.Find(&list).Error
	if err != nil {
		return
	}

	return
}
